import matplotlib.pyplot as plt
# from time import time
from datetime import datetime, time
from read_excel import ReadExcel

# 提供的时间数据
# time_data = [
#     "20:25:59", "20:13:30", "17:11:59", "22:00:50", "21:49:59", "21:49:59",
#     "21:20:52", "20:39:50", "20:31:35", "20:25:51", "20:17:24", "19:06:01",
#     "18:23:05", "17:52:11", "17:48:43", "17:10:10", "22:06:22", "20:25:59",
#     # ... 更多时间数据
# ]
time_list = []
time_data = ReadExcel('交易时间.xlsx')

count = time_data.shape[0]

time_arr = time_data.iloc[2:count, 1:2].values.tolist()
# 时间间隔
INTERVAL = 15

for item in time_arr:
    # print(type[item[0]])
    if isinstance(item[0], datetime):
        dt_str = item[0].strftime('%Y-%m-%d %H:%M:%S')[11:]
    else:
        dt_str = item[0][11:]
    time_list.append(dt_str)

# 筛选17点到23点的数据
filtered_time_data = [time for time in time_list if 17 <= int(time.split(":")[0]) <= 23]

# 将时间字符串转换为datetime.time对象
time_objects = [datetime.strptime(t, "%H:%M:%S").time() for t in filtered_time_data]
time_objects.sort()
# 按半小时分组
half_hour_groups = {}
for t in time_objects:
    half_hour_key = ((t.hour * 60 + t.minute) // INTERVAL) * INTERVAL
    group_time = time(half_hour_key // 60, half_hour_key % 60).strftime('%H:%M')
    half_hour_groups[group_time] = half_hour_groups.get(group_time, 0) + 1

# 提取半小时分组及其对应的计数
half_hours = list(half_hour_groups.keys())
counts = list(half_hour_groups.values())

plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置字体为黑体
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号
# 绘制柱状图
plt.figure(figsize=(10, 6))
plt.bar(half_hours, counts, width=0.2)
plt.xlabel('半小时分组 (分钟)')
plt.ylabel('计数')
plt.title('半小时分组计数')
plt.xticks(half_hours, rotation=45)
plt.grid(axis='y')

# 保存图片
plt.savefig('test.png')
print('图片已保存')
# 显示图表
plt.show()
